<template>
  <Dialog title="选择项目供应商" v-model="dialogVisible" width="60%" :close="close">
    <el-row>
      <el-col :span="14">
        <el-card>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="85px"
          >
            <el-form-item prop="supplierName">
              <el-input
                v-model="queryParams.supplierName"
                placeholder="请输入供应商名称"
                clearable
                @keyup.enter="handleQuery"
                class="!w-180px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery"> 搜索 </el-button>
              <el-button @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="list"
            :show-overflow-tooltip="true"
            :header-cell-style="{ background: '#f5f7fa' }"
            @row-click="handleRowClick"
            @selection-change="handleSelectionChange"
            border
            ref="tableRef"
            height="300px"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="供应商名称" align="center" prop="supplierName" />
            <el-table-column label="统一社会信用代码" align="center" prop="creditCode" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card>
          <h3>已选择({{ selectedItems.length }})</h3>
          <div class="tag-container">
            <el-tag
              v-for="tag in selectedItems"
              :key="tag.supplierId"
              closable
              effect="dark"
              @close="removeSelectedItem(tag)"
              class="tag-item"
            >
              {{ tag.supplierName }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <template #footer>
      <el-button type="primary" @click="confirmSelection">确认</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ProjectSupplierApi, ProjectSupplierVO, SeletSupplierVO } from '@/api/rep/projectsupplier'
import { ElTable } from 'element-plus'

/** 供应商选择 */
defineOptions({ name: 'SupplierSelect' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false)
const loading = ref(false) // 列表的加载中
const list = ref<ProjectSupplierVO[]>([]) // 列表的数据
const queryParams = reactive({
  supplierName: ''
})
const queryFormRef = ref() // 搜索的表单
const formData = ref()

const tableRef = ref<typeof ElTable>() // 表格的 Ref
const selectedItems = ref<SeletSupplierVO[]>([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const filteredList = await ProjectSupplierApi.getProjectSupplierRespList(queryParams)
    list.value = filteredList
    // 更新列表显示，并设置默认选中项
    updateTableSelection(filteredList)
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async (data: Array<SeletSupplierVO>) => {
  dialogVisible.value = true
  const dataList: SeletSupplierVO[] = []
  data?.forEach((item) => {
    if (item) {
      const ret: SeletSupplierVO = {
        supplierId: item.supplierId,
        supplierName: item.supplierName,
        creditCode: item.creditCode
      }
      dataList.push(ret)
    }
  })
  selectedItems.value = dataList
}
defineExpose({ open })

/** 关闭弹窗 */
const close = () => {
  dialogVisible.value = false
  selectedItems.value = []
  queryParams.supplierName = ''
  list.value = []
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 更新表格的选中项 */
const updateTableSelection = (newList: ProjectSupplierVO[]) => {
  // 清除当前所有选中项
  unref(tableRef)?.clearSelection()
  // 遍历新列表，设置已选择项的选中状态
  newList.forEach((item) => {
    const selectedItem = selectedItems.value.find((selected) => selected.supplierId === item.id)
    if (selectedItem) {
      nextTick(() => {
        unref(tableRef)?.toggleRowSelection(item, true) // 选中该行
      })
    }
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 处理某一行的点击 */
const handleRowClick = (row) => {
  unref(tableRef)?.toggleRowSelection(row)
}

/** 多选框选中数据 */
const handleSelectionChange = (values) => {
  const newSelection = [...selectedItems.value]
  values.forEach((val) => {
    const item = {
      supplierId: val.id,
      supplierName: val.supplierName,
      creditCode: val.creditCode
    }
    if (!newSelection.some((selected) => selected.supplierId === item.supplierId)) {
      newSelection.push(item)
    }
  })
  selectedItems.value = newSelection
}

/** 删除选中数据 */
const removeSelectedItem = (supplier: SeletSupplierVO) => {
  const newSelection = [...selectedItems.value].filter(
    (item) => item.supplierId !== supplier.supplierId
  )
  selectedItems.value = newSelection

  // 清除表格的所有选中项
  if (list.value.length > 0) {
    unref(tableRef)?.clearSelection()

    // 重新设置表格的选中项
    newSelection.forEach((item) => {
      unref(tableRef)?.toggleRowSelection(
        list.value.find((row) => row.id === item.supplierId),
        true
      )
    })
  }
}

const emit = defineEmits(['selectData'])

/** 确认按钮 */
const confirmSelection = () => {
  if (selectedItems.value.length === 0) {
    message.warning('请选择至少一个供应商')
    return
  }
  const dataList: SeletSupplierVO[] = []
  const seen: Record<string, boolean> = {}

  // 处理selectedItems
  selectedItems.value.forEach((item) => {
    if (item) {
      const key = `${item.supplierId}` // 创建唯一键，基于supplierId和supplierType
      if (!seen[key]) {
        // 检查是否已经添加过
        seen[key] = true // 标记为已添加
        const ret: SeletSupplierVO = {
          supplierId: item.supplierId,
          supplierName: item.supplierName,
          creditCode: item.creditCode
        }
        dataList.push(ret)
      }
    }
  })

  formData.value = dataList
  console.log('选择供应商-完成', formData.value)
  emit('selectData', formData.value)
  //关闭弹
  close()
}
</script>
<style scoped>
.tag-container {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}
.tag-item {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
